package com.clstu.datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.testng.annotations.Test;

import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 老牌连接池技术,spring底层现在还是用到它,
 * c3p0入门案例(连接池技术,提高效率的同时
 * 还能够避免mysql因为没有连接数的控制而崩溃的问题)
 */
public class C3p0_ {

    @Test//测试连接,测试c3p0连接池方式连接mysql5000次耗时
    public void testConnect() throws IOException, PropertyVetoException, SQLException {
        //创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();//c3p0.jar包里面的,实现了DataSource接口
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        //注意:连接管理是右 comboPooledDataSource来完成的
        //手动配置
        comboPooledDataSource.setDriverClass(driver);//传入驱动
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);
        //设置初始化连接池数量
        comboPooledDataSource.setInitialPoolSize(10);
        //设置最大连接池数量,如果连接超过了这个数量,后面的就需要进入等待队列,等空出来后再连接
        comboPooledDataSource.setMaxPoolSize(50);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            Connection connection = comboPooledDataSource.getConnection();
            connection.close();//用完之后放回连接池
        }
        long end = System.currentTimeMillis();
        System.out.println("c3p0连接池5000次耗时===="+(end-start)+"ms");//362ms提升还是很大的近20倍的速度
    }

    @Test//第二种方式,用配置文件src\\c3p0-config.xml直接连接(普遍一些)
    public void Method2() throws SQLException {
        //自动配置
        ComboPooledDataSource along = new ComboPooledDataSource("along");//通过配置文件一步就完成了,
        //测试5000次连接用时
        long start = System.currentTimeMillis();//
        for (int i = 0; i < 500000; i++) {
            Connection connection = along.getConnection();
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("配置文件c3p0连接5000耗时:====="+(end-start)+"ms");//338ms跟上面差不多(本质上还是一样的)
        System.out.println("配置文件c3p0连接500000耗时:====="+(end-start)+"ms");//1904ms
    }
}
